/**
 * 
 */
package com.asset.salesforce.controller.ajax;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.domain.Account;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.dto.table.AccountData;
import com.asset.salesforce.dto.table.ReadOperationParams;
import com.asset.salesforce.dto.table.ReadOperationResults;
import com.asset.salesforce.service.AccountService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;

// TODO: Auto-generated Javadoc
/**
 *
 * @author Hisham Mounir
 * this controller class is used to handle account requests
 */
@Controller
public class AccountRestController {

	/** The account service. */
	@Autowired
	private AccountService accountService;
	
	/** The contact service. */
	@Autowired
	private ContactService contactService;
	
	/** The employee service. */
	@Autowired
	private EmployeeService employeeService;
	
	/**
	 * List.
	 *
	 * @param params the params
	 * @param session the session
	 * @return the read operation results
	 */
	@RequestMapping(value = "/accountsList", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	ReadOperationResults list(ReadOperationParams params,HttpSession session) {
		ReadOperationResults result = new ReadOperationResults();
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		
		String sortDir = params.getsSortDir_0();
		String sortColName = params.getsColumns().split(",")[params.getiSortCol_0()];
		String column=null;
		if(sortColName.equals("id")){
			column="id";
		}
		if(sortColName.equals("accounName")){
			column="accountName";
		}
		if(sortColName.equals("accountCompany")){
			column="companyName";
		}
		if(sortColName.equals("accountOwner")){
			column="accountCreator.fName";
		}
		
		List<Account>allLeads = new ArrayList<Account>();
		if(userDetails.getIsOwner()==true){
			allLeads = accountService.getAllAccountByCompany(params.getsSearch(),userDetails.getCompany().getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = accountService.getAllSizeForOwner(params.getsSearch(),userDetails.getCompany().getCompanyName());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}
		else{
			allLeads = accountService.getAllAccountByEmployee(params.getsSearch(),userDetails.getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = accountService.getAllSizeForEmployee(params.getsSearch(),userDetails.getId());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}        
        result.setsEcho(params.getsEcho());
        List<AccountData>leadData = new ArrayList<AccountData>();
		for (Account lead : allLeads) {
			AccountData data = new AccountData();
			data.setId(lead.getId());
			data.setAccountCompany(lead.getCompanyName());
			data.setAccounName(lead.getAccountName());
			if(lead.getAccountCreator()!=null){
				Employee employee = employeeService.getById(lead.getAccountCreator().getId());
				data.setAccountOwner(employee.getfName()+" "+employee.getlName());
			}
			
			leadData.add(data);
		}
        result.setAaData(leadData);
        return result;
	}
	
	/**
	 * Delete.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param id the id
	 * @return true, if successful
	 */
	@RequestMapping(value = "/deleteAccount", method = RequestMethod.POST)
	@ResponseBody
	public boolean delete(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer id) {
		if (SecurityUtils.getSubject().hasRole("accountDelete")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			 Account account = accountService.getById(id);
			 account.setIsDeleted(true);
			 account.setDateModified(new Date());
			 accountService.saveOrupdate(account);
			 List<Contact>contacts = contactService.getContactsByParentType(account.getId(), "lead");
			 if(contacts!=null){
				 for (Contact contact : contacts) {
					 contact.setIsDeleted(true);
					 contact.setDateModified(new Date());
					 contactService.saveOrupdate(contact);
				}
			 }
			 response.setStatus(HttpServletResponse.SC_OK);
				return true;
			}
			else{
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return false;
			}	
	}
}
